package com.virjar.dungproxy.client.ippool.strategy.impl;

import com.virjar.dungproxy.client.httpclient.HttpInvoker;
import com.virjar.dungproxy.client.ippool.config.ProxyConstant;
import com.virjar.dungproxy.client.ippool.strategy.ProxyChecker;
import com.virjar.dungproxy.client.model.AvProxyVO;
import com.virjar.dungproxy.client.util.RedisTools;
import org.apache.commons.lang3.StringUtils;


/**
 * 默认的通过内容校验器
 *
 * @author mario1oreo
 * @date 2018-1-10 12:24:13
 */
public class DefaultContentProxyChecker implements ProxyChecker {

    private volatile String expectContent;

    private volatile String userID;

    private volatile String domain;

    private static RedisTools redisTools = new RedisTools();

    public DefaultContentProxyChecker(String expectContent, String userID, String domain) {
        this.expectContent = expectContent;
        this.userID = userID;
        this.domain = domain;
    }

    private String getExpectContent() {
        return this.expectContent;
    }

    public String getUserID() {
        return userID;
    }

    public String getDomain() {
        return domain;
    }

    @Override
    public boolean available(AvProxyVO avProxyVO, String url) {
        boolean isPass = false;
        for (int i = 0; i < 3; i++) {
            if (StringUtils.isNotBlank(getExpectContent())) {
                String response = HttpInvoker.get(url, avProxyVO.getIp(), avProxyVO.getPort());
                if (StringUtils.isNotEmpty(response) && StringUtils.contains(response, getExpectContent())) {
                    isPass = true;
                    break;
                }
            } else if (HttpInvoker.getStatus(url, avProxyVO.getIp(), avProxyVO.getPort()) == 200) {
                isPass = true;
                break;
            }
        }
        if (isPass && StringUtils.isNotBlank(getUserID())) {
            String availableProxyListKey = ProxyConstant.AVAILABLE_PROXY_LIST + getUserID() + ProxyConstant.UNDER_LINE + getDomain();
            String proxyScoreSortSetKey = ProxyConstant.PROXY_SCORE_SORT_SET + getUserID() + ProxyConstant.UNDER_LINE + getDomain();
            String ipPort = avProxyVO.getIp() + ProxyConstant.COLON + avProxyVO.getPort();
            redisTools.rpushStr(availableProxyListKey, ipPort);
            redisTools.zaddSortSet(proxyScoreSortSetKey, 0.5, ipPort);
        }
        return isPass;
    }
}
